/**
 * 导出工具类 - 用于导出项目报表
 */

import type { Project } from '../types/workItem';
import dayjs from 'dayjs';

export interface ProjectReportData {
  项目名称: string;
  标识符: string;
  项目类型: string;
  状态: string;
  可见性: string;
  负责人: string;
  创建人: string;
  开始时间: string;
  结束时间: string;
  创建时间: string;
  更新时间: string;
  是否归档: string;
  是否删除: string;
  描述: string;
}

export class ExportUtils {
  // 项目类型映射
  private static projectTypeMap: Record<string, string> = {
    scrum: 'Scrum',
    kanban: '看板',
    waterfall: '瀑布',
    hybrid: '混合',
  };

  // 状态类型映射
  private static projectStateMap: Record<string, string> = {
    pending: '待处理',
    in_progress: '进行中',
    completed: '已完成',
  };

  /**
   * 将项目数据转换为报表格式
   */
  static convertProjectsToReportData(projects: Project[]): ProjectReportData[] {
    return projects.map(project => ({
      项目名称: project.name || '',
      标识符: project.identifier || '',
      项目类型: this.projectTypeMap[project.type] || project.type || '',
      状态: this.projectStateMap[project.state?.type] || project.state?.name || '',
      可见性: project.visibility === 'public' ? '公开' : '私有',
      负责人: project.assignee?.display_name || '未分配',
      创建人: project.created_by?.display_name || '未知',
      开始时间: project.start_at ? dayjs(project.start_at * 1000).format('YYYY-MM-DD') : '',
      结束时间: project.end_at ? dayjs(project.end_at * 1000).format('YYYY-MM-DD') : '',
      创建时间: project.created_at ? dayjs(project.created_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '',
      更新时间: project.updated_at ? dayjs(project.updated_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '',
      是否归档: project.is_archived ? '是' : '否',
      是否删除: project.is_deleted ? '是' : '否',
      描述: project.description || '',
    }));
  }

  /**
   * 导出为CSV格式
   */
  static exportToCSV(data: ProjectReportData[], filename: string = '项目报表'): void {
    if (data.length === 0) {
      throw new Error('没有数据可导出');
    }

    // 获取表头
    const headers = Object.keys(data[0]);
    
    // 构建CSV内容
    const csvContent = [
      // 表头
      headers.join(','),
      // 数据行
      ...data.map(row => 
        headers.map(header => {
          const value = row[header as keyof ProjectReportData];
          // 处理包含逗号、换行符或引号的值
          if (typeof value === 'string' && (value.includes(',') || value.includes('\n') || value.includes('"'))) {
            return `"${value.replace(/"/g, '""')}"`;
          }
          return value;
        }).join(',')
      )
    ].join('\n');

    // 添加BOM以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${filename}_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }

  /**
   * 导出为Excel格式 (实际上是CSV，但可以被Excel打开)
   */
  static exportToExcel(data: ProjectReportData[], filename: string = '项目报表'): void {
    this.exportToCSV(data, filename);
  }

  /**
   * 导出为JSON格式
   */
  static exportToJSON(data: ProjectReportData[], filename: string = '项目报表'): void {
    if (data.length === 0) {
      throw new Error('没有数据可导出');
    }

    const jsonContent = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' });
    
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `${filename}_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.json`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }

  /**
   * 生成项目统计信息
   */
  static generateProjectStatistics(projects: Project[]): {
    总项目数: number;
    项目类型统计: Record<string, number>;
    状态统计: Record<string, number>;
    可见性统计: Record<string, number>;
    归档统计: Record<string, number>;
  } {
    const stats = {
      总项目数: projects.length,
      项目类型统计: {} as Record<string, number>,
      状态统计: {} as Record<string, number>,
      可见性统计: {} as Record<string, number>,
      归档统计: {} as Record<string, number>,
    };

    projects.forEach(project => {
      // 项目类型统计
      const type = this.projectTypeMap[project.type] || project.type || '未知';
      stats.项目类型统计[type] = (stats.项目类型统计[type] || 0) + 1;

      // 状态统计
      const state = this.projectStateMap[project.state?.type] || project.state?.name || '未知';
      stats.状态统计[state] = (stats.状态统计[state] || 0) + 1;

      // 可见性统计
      const visibility = project.visibility === 'public' ? '公开' : '私有';
      stats.可见性统计[visibility] = (stats.可见性统计[visibility] || 0) + 1;

      // 归档统计
      const archived = project.is_archived ? '已归档' : '未归档';
      stats.归档统计[archived] = (stats.归档统计[archived] || 0) + 1;
    });

    return stats;
  }
}